package csu.jpetstore.jpetstore.utils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.*;


@Component
@Lazy(value = false)
public class MailUtils {
    @Autowired
    private JavaMailSender jms;
    @Autowired
    private TemplateEngine templateEngine;


    public void send(String receiver, String title, Map<String, Object> text) throws MessagingException {
        class text{
            String username;
            String context;
            String time;
        }
        MimeMessage mimeMessage =jms.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
        mimeMessageHelper.setFrom("mrchendao@163.com");
        mimeMessageHelper.setTo(receiver);
        mimeMessageHelper.setSubject(title);

        // 利用 Thymeleaf 模板构建 html 文本
        Context ctx = new Context();
        // 给模板的参数的上下文
        ctx.setVariables(text);
        // 执行模板引擎，执行模板引擎需要传入模板名、上下文对象
        // Thymeleaf的默认配置期望所有HTML文件都放在 **resources/templates ** 目录下，以.html扩展名结尾。
        String emailText = templateEngine.process("mail", ctx);
//        String emailText = templateEngine.process(template, ctx);
        mimeMessageHelper.setText(emailText, true);
        jms.send(mimeMessage);
    }
}
